package com.guodaxia.gzh.web;

import com.alibaba.fastjson.JSON;
import com.guodaxia.gzh.common.Ajax;
import com.guodaxia.gzh.config.WechatConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/wechat/")
@ResponseBody
public class WetchatRest {

    @Autowired
    WechatConfig wechatConfig;

//    @Qualifier(value = "proxy")
    @Autowired
    RestTemplate restTemplate;

    /**
     * 微信转发的接口
     *
     * @param wechatReqDTO
     * @return
     */
    @PostMapping("convert")
    public Ajax wechatInterface(@RequestBody wechatReqDTO<Map<String, Object>> wechatReqDTO) {
        String path = wechatReqDTO.getPath();
        String realUrl = wechatConfig.getUrls().get(path);
        if (Strings.isEmpty(realUrl)) {
            return Ajax.error("微信接口名称【" + path + "】未配置！");
        }
        wechatReqDTO.getParams().put("appid",wechatConfig.getLailiao().get("appId"));
        wechatReqDTO.getParams().put("secret",wechatConfig.getLailiao().get("appsecret"));
        String[] api = realUrl.split("###");
        String res = "";
        if ("GET".equals(api[0])) {
            api[1] = api[1] + "?";
            for (String keyName : wechatReqDTO.getParams().keySet()) {
                api[1] = api[1] + keyName + "=" + wechatReqDTO.getParams().get(keyName) + "&";
            }
            if (api[1].charAt(api[1].length() - 1) == '&') {
                api[1] = api[1].substring(0, api[1].length() - 1);
            }
            res = restTemplate.getForObject(api[1], String.class);
        } else if ("POST".equals(api[0])) {
            res = restTemplate.postForObject(api[1], wechatReqDTO.getParams(), String.class);
        }
        Map resMap = JSON.parseObject(res, Map.class);
        assert resMap != null;
        if (resMap.containsKey("errcode")) {
            return Ajax.error((String) resMap.get("errmsg"));
        }
        return Ajax.ok(resMap);
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class wechatReqDTO<T> {
    String path; //实际微信接口最后的path
    T params;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class WechatResDTO {
    String errcode;
    String errmsg;
    String rid;
}

